package com.aj.activity;

import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

import org.json.JSONException;
import org.json.JSONObject;

import com.aj.application.LoveHomeApplication;
import com.aj.databases.dao.AccountDao;
import com.aj.databases.dao.UserDao;
import com.aj.databases.entry.Account;
import com.aj.databases.entry.User;
import com.aj.http.AsynchronizationHttpRequest.IHttpCallBack;
import com.aj.http.request.GetMarryDateRequest;
import com.aj.http.request.SaveMarryRequest;
import com.aj.http.response.BaseRespond;
import com.aj.http.response.Common;
import com.aj.http.response.MarryDateResponse;
import com.aj.utils.DateUtils;

import android.app.DatePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class HomesMarryActivity extends TitleBarBaseActivity implements OnClickListener, TextWatcher {

    private static final String TAG = HomesMarryActivity.class.getName();
    private EditText mEditText;
    private Button mSaveButton;
    private ImageView marrydate_image;

    public static void newInstance(Context context) {
        Intent intent = new Intent(context, HomesMarryActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.homes_marry_layout);
        initPageTitleBars();
        initViews();
        getMarryDate();
    }

    private void initPageTitleBars() {
        setTitle(R.string.home_memorial_day_text);
        TextView backButton = getTitleLeftButton();
        backButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    private void initViews() {
        mEditText = (EditText) findViewById(R.id.wedding_edittext);
        mEditText.setOnClickListener(this);
        mEditText.addTextChangedListener(this);
        mSaveButton = (Button) findViewById(R.id.wedding_save_btn);
        mSaveButton.setEnabled(false);
        mSaveButton.setOnClickListener(this);
        marrydate_image = (ImageView) findViewById(R.id.marrydate_image);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.wedding_edittext:
            createMarryDatePickerDialog();
            break;

        case R.id.wedding_save_btn:
            String marryDate = mEditText.getText().toString().trim();
            if (marryDate != null) {
                saveMarryDate(marryDate);
            } else {
                Toast.makeText(HomesMarryActivity.this, "请选择结婚日期", Toast.LENGTH_LONG).show();
            }

            break;

        default:
            break;
        }
    }

    private void saveMarryDate(String marryDate) {
        if (LoveHomeApplication.token != null && LoveHomeApplication.token.trim().length() > 0) {
            AccountDao accountDao = new AccountDao(this);
            UserDao userDao = new UserDao(this);
            Account account = accountDao.getByToken(LoveHomeApplication.token);
            if (account != null) {
                User user = userDao.getUserByUserId(account.getLast_used_user_id());
                if (user != null) {
                    showProgressDialog("正在保存，请稍后...");
                    SaveMarryRequest request = new SaveMarryRequest();
                    request.excute(this, user.getUser_id(), marryDate, new IHttpCallBack() {

                        @Override
                        public void success(String result) {
                            try {
                                Common response = new Common(new JSONObject(result));
                                String code = response.getReturnCode().trim();
                                if (BaseRespond.SUCCESS_RESULT_CODE_STRING.equals(code)) {
                                    getMarryDate();
                                } else {
                                    Toast.makeText(HomesMarryActivity.this, response.getErrorMsg(), Toast.LENGTH_LONG).show();
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            dimissProgressDialog();
                        }

                        @Override
                        public void fail(String result) {
                            try {
                                Common common = new Common(new JSONObject(result));
                                if (common != null) {
                                    Log.e(TAG, "message:" + common.getErrorMsg());
                                    Toast.makeText(HomesMarryActivity.this, common.getErrorMsg(), Toast.LENGTH_SHORT).show();
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            dimissProgressDialog();
                        }

                    });
                }
            }
        }

    }

    private void createMarryDatePickerDialog() {
        // 初始化Calendar日历对象
        Calendar calendar = Calendar.getInstance(Locale.CHINA);
        Date date = new Date(); // 获取当前日期Date对象
        calendar.setTime(date); // 为Calendar对象设置时间为当前日期
        int mYear = calendar.get(Calendar.YEAR); // 获取Calendar对象中的年
        int mMonth = calendar.get(Calendar.MONTH);// 获取Calendar对象中的月
        int mDay = calendar.get(Calendar.DAY_OF_MONTH);// 获取这个月的第几天

        DatePickerDialog dpd = new DatePickerDialog(this, marryDatelistener, mYear, mMonth - 1, mDay);
        dpd.show();
    }

    private DatePickerDialog.OnDateSetListener marryDatelistener = new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
            String marryDate = year + "-" + (monthOfYear + 1) + "-" + dayOfMonth;
            mEditText.setText(marryDate);
        }
    };

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        if (s.length() > 0) {
            mSaveButton.setBackgroundResource(R.drawable.ok_btn_selector);
            mSaveButton.setEnabled(true);
        } else {
            mSaveButton.setBackgroundResource(R.drawable.cancel_btn_selector);
            mSaveButton.setEnabled(false);
        }
    }

    @Override
    public void afterTextChanged(Editable s) {

    }

    private void setMarryDateImages(int years) {
        switch (years) {
        case 0:
            marrydate_image.setBackgroundResource(R.drawable.year0);
            break;
        case 1:
            marrydate_image.setBackgroundResource(R.drawable.year1);
            break;
        case 2:
            marrydate_image.setBackgroundResource(R.drawable.year2);
            break;
        case 3:
            marrydate_image.setBackgroundResource(R.drawable.year3);
            break;
        case 4:
            marrydate_image.setBackgroundResource(R.drawable.year4);
            break;
        case 5:
            marrydate_image.setBackgroundResource(R.drawable.year5);
            break;
        case 6:
            marrydate_image.setBackgroundResource(R.drawable.year6);
            break;
        case 7:
            marrydate_image.setBackgroundResource(R.drawable.year7);
            break;
        case 8:
            marrydate_image.setBackgroundResource(R.drawable.year8);
            break;
        case 9:
            marrydate_image.setBackgroundResource(R.drawable.year9);
            break;
        case 10:
            marrydate_image.setBackgroundResource(R.drawable.year10);
            break;
        case 11:
            marrydate_image.setBackgroundResource(R.drawable.year11);
            break;
        case 12:
            marrydate_image.setBackgroundResource(R.drawable.year12);
            break;
        case 13:
            marrydate_image.setBackgroundResource(R.drawable.year13);
            break;
        case 14:
            marrydate_image.setBackgroundResource(R.drawable.year14);
            break;
        case 15:
            marrydate_image.setBackgroundResource(R.drawable.year15);
            break;
        case 20:
            marrydate_image.setBackgroundResource(R.drawable.year20);
            break;
        case 25:
            marrydate_image.setBackgroundResource(R.drawable.year25);
            break;
        case 30:
            marrydate_image.setBackgroundResource(R.drawable.year30);
            break;
        case 35:
            marrydate_image.setBackgroundResource(R.drawable.year35);
            break;
        case 40:
            marrydate_image.setBackgroundResource(R.drawable.year40);
            break;
        case 45:
            marrydate_image.setBackgroundResource(R.drawable.year45);
            break;
        case 50:
            marrydate_image.setBackgroundResource(R.drawable.year50);
            break;
        case 55:
            marrydate_image.setBackgroundResource(R.drawable.year55);
            break;
        default:
            marrydate_image.setBackgroundResource(R.drawable.year60_75);
            break;
        }

    }

    private void getMarryDate() {
        if (LoveHomeApplication.token != null && LoveHomeApplication.token.trim().length() > 0) {
            AccountDao accountDao = new AccountDao(this);
            UserDao userDao = new UserDao(this);
            Account account = accountDao.getByToken(LoveHomeApplication.token);
            if (account != null) {
                User user = userDao.getUserByUserId(account.getLast_used_user_id());
                if (user != null) {
                    showProgressDialog("正在获取结婚日期，请稍后...");
                    GetMarryDateRequest request = new GetMarryDateRequest();
                    request.excute(this, user.getUser_id(), new IHttpCallBack() {

                        @Override
                        public void success(String result) {
                            try {
                                MarryDateResponse response = new MarryDateResponse(new JSONObject(result));
                                String code = response.getCommon().getReturnCode();
                                if (BaseRespond.SUCCESS_RESULT_CODE_STRING.equals(code)) {
                                    long marryDate = DateUtils.getTime(response.getMarrieddate());
                                    int year = DateUtils.getAge(marryDate);
                                    setMarryDateImages(year);
                                }

                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            dimissProgressDialog();
                        }

                        @Override
                        public void fail(String result) {
                            try {
                                Common common = new Common(new JSONObject(result));
                                if (common != null) {
                                    Log.e(TAG, "message:" + common.getErrorMsg());
                                    Toast.makeText(HomesMarryActivity.this, common.getErrorMsg(), Toast.LENGTH_SHORT).show();
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            dimissProgressDialog();
                        }

                    });
                }
            }
        }
    }
}
